//
//  CityTViewController.m
//  OneDay
//
//  Created by lanou3g on 15/10/28.
//  Copyright © 2015年 oneDay. All rights reserved.
//

#import "CityTViewController.h"
#import "PartyTableViewCell.h"
#import "PartyDetailViewController.h"

@interface CityTViewController ()<MONActivityIndicatorViewDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) MONActivityIndicatorView *indicatorView;

@end

@implementation CityTViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // 没有数据的时候为白色，没有线条
    self.tableView.separatorStyle = NO;
    
    [self setUp];
    
    // 开始加载动画
    [self addIndicatorView];
    [_indicatorView startAnimating];
    
    self.page = 1;
    NSString *requsestUrl = [kCityOneUrl stringByAppendingString:[NSString stringWithFormat:@"%ld&category=all&lat=40.030633&city_id=%ld", self.page,self.needID]];
    self.dataArray = [NSMutableArray array];
    [self requestFirstPartyDataWithUrl:requsestUrl block:^(NSArray *array) {
        [self.dataArray addObjectsFromArray:array];
        [self.tableView reloadData];
        [_indicatorView stopAnimating];
    }];
    
}



#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"StyleT1";
    self.tableView.separatorStyle = NO;
    PartyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[PartyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
    }
    // 取消选中的颜色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (self.dataArray.count > 0) {
        PartyModel *model = self.dataArray[indexPath.row];
        cell.model = model;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PartyDetailViewController *detailVC = [[PartyDetailViewController alloc] init];
    PartyModel *model = self.dataArray[indexPath.row];
    detailVC.leo_id = model.leo_id;
    [self.navigationController pushViewController:detailVC animated:YES];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 0.85 * kWidth;
}
- (void)setUp
{
    // 下拉刷新
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.footer = [MJRefreshBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    // 进入刷新状态
    [self.tableView.header beginRefreshing];
}
- (void)footerRefresh
{
    self.page++;
    NSString *strUrl = [kCityOneUrl stringByAppendingString:[NSString stringWithFormat:@"%ld&category=all&lat=40.030633&city_id=%ld", self.page,self.needID]];
    [self requestFirstPartyDataWithUrl:strUrl block:^(NSArray *array) {
        if (array != nil) {
            [self.dataArray addObjectsFromArray:array];
            [self.tableView reloadData];
        }else{
            NSLog(@"没有数据了");
        }
    }];
    [self.tableView.footer endRefreshing];
    
}

- (void)headerRefresh
{
    // 在这个方法中请求数据
    // 结束刷新状态
    
    [self.tableView.header endRefreshing];
}

#pragma mark -- 隐藏tabBar
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}


#pragma mark - 请求数据
- (void)requestFirstPartyDataWithUrl:(NSString *)url block:(void (^)(NSArray *array))block
{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        [request setHTTPMethod:@"GET"];
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (data != nil) {
                NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSArray *array = rootDic[@"result"];
                // 初始化数组
                NSMutableArray *tempArray = [NSMutableArray array];
                // 遍历
                for (NSDictionary *dic in array) {
                    PartyModel *model = [[PartyModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [tempArray addObject:model];
                }
                PartyModel *model = [tempArray firstObject];
                if ([model.item_type isEqualToString:@"event"]) {
                    [tempArray removeObject:model];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    block(tempArray);
                });
            }
        }];
        [dataTask resume];
    });
}

#pragma mark - 添加加载等待动画
- (void)addIndicatorView
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.center = self.view.center;
    _indicatorView.delegate = self;
    
    _indicatorView.numberOfCircles = 5; // 圆点个数
    _indicatorView.internalSpacing = 5; // 圆点之间的距离
    _indicatorView.radius = 6; // 圆点半径
    //    _indicatorView.delay = 0;
    
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}

#pragma mark - 加载等待动画的代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    switch (index) {
        case 0:
            return [UIColor redColor];
            break;
        case 1:
            return [UIColor magentaColor];
            break;
        case 2:
            return [UIColor orangeColor];
            break;
        case 3:
            return [UIColor purpleColor];
            break;
        default:
            return [UIColor yellowColor];
            break;;
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
